import { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from './useAuth';
import { getSubscriptionPath } from '@/utils/userUtils';

/**
 * 用户头像和个人资料相关的自定义 Hook
 * 统一管理用户头像下拉菜单、登录/登出逻辑等共同功能
 */
export const useUserProfile = () => {
  const navigate = useNavigate();
  const { 
    isLoggedIn, 
    userData, 
    showLoginModal, 
    isRegisterMode, 
    openLoginModal, 
    closeLoginModal, 
    handleLoginSuccess, 
    logout,
    refreshUserData // 从useAuth中获取刷新用户数据的函数
  } = useAuth();
  
  // 下拉菜单相关状态和引用
  const [showLogoutButton, setShowLogoutButton] = useState(false);
  const logoutRef = useRef<HTMLDivElement>(null);
  const avatarBtnRef = useRef<HTMLDivElement>(null);

  // 点击外部关闭下拉菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        logoutRef.current &&
        !logoutRef.current.contains(event.target as Node) &&
        avatarBtnRef.current &&
        !avatarBtnRef.current.contains(event.target as Node)
      ) {
        setShowLogoutButton(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  // 登录按钮点击处理
  const handleLoginClick = () => {
    openLoginModal(false);
  };

  // 注册按钮点击处理
  const handleRegisterClick = () => {
    openLoginModal(true);
  };

  // 登录成功并更新tab的处理
  const handleLoginSuccessAndUpdateTab = (setActiveTab?: (tab: string) => void) => {
    const userDataStr = localStorage.getItem('userData');
    if (userDataStr && setActiveTab) {
      try {
        const userData = JSON.parse(userDataStr);
        localStorage.setItem('last_chat_type', userData.last_chat_type || 'anime_girl');
        setActiveTab(userData.last_chat_type || 'anime_girl');
      } catch (error) {
        console.error('Failed to parse user data:', error);
      }
    }
    handleLoginSuccess();
  };

  // 登出确认弹窗的状态
  const [showLogoutConfirm, setShowLogoutConfirm] = useState(false);

  // 展示登出确认弹窗
  const handleLogoutClick = () => {
    setShowLogoutButton(false);
    setShowLogoutConfirm(true);
  };

  // 确认登出处理
  const confirmLogout = () => {
    setShowLogoutConfirm(false);
    logout();
    navigate('/');
  };

  // 取消登出处理
  const cancelLogout = () => {
    setShowLogoutConfirm(false);
  };

  // 头像图片处理函数
  const withAvatarResize = (url: string) => {
    // 这里可以实现图片尺寸调整逻辑
    return url;
  };

  // 切换用户头像下拉菜单
  const toggleProfileDropdown = (e: React.MouseEvent) => {
    e.stopPropagation();
    // 设置小延迟避免与点击外部处理器冲突
    setTimeout(() => {
      setShowLogoutButton(s => !s);
    }, 10);
  };

  // 头像更新成功后的处理函数
  const handleAvatarUpdated = () => {
    // 刷新用户数据以获取最新的头像
    if (refreshUserData) {
      refreshUserData();
    }
  };

  return {
    // 认证相关状态
    isLoggedIn,
    userData,  
    showLoginModal,
    isRegisterMode,
    
    // 下拉菜单相关
    showLogoutButton,
    logoutRef,
    avatarBtnRef,
    
    // 登出确认弹窗相关
    showLogoutConfirm,
    setShowLogoutConfirm,
    confirmLogout,
    cancelLogout,
    
    // 处理函数
    handleLoginClick,
    handleRegisterClick,
    handleLoginSuccessAndUpdateTab,
    handleLogoutClick,
    withAvatarResize,
    toggleProfileDropdown,
    closeLoginModal,
    openLoginModal,
    handleAvatarUpdated, // 新增头像更新处理函数
    
    // 导航函数
    navigateToSubscription: () => navigate(getSubscriptionPath()),
  };
}; 